import { Component, OnInit, ViewChild } from "@angular/core";
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config } from "../../shared/smartadmin.config";

declare var $: any;
@Component({
  selector: "sa-weight-data",
  templateUrl: "./weight-data.component.html",
  styleUrls: ["./weight-data.component.css"],
})
export class WeightDataComponent implements OnInit {
  validatorOptions = {
    feedbackIcons: {
      valid: "glyphicon glyphicon-ok",
      invalid: "glyphicon glyphicon-remove",
      validating: "glyphicon glyphicon-refresh",
    },
    fields: {
      carNumber: {
        validators: {
          notEmpty: {
            message: "请输入车牌号码",
          },
        },
      },
      uploadDate: {
        validators: {
          notEmpty: {
            message: "请选择称重过磅时间",
          },
        },
      },
    },
  };
  tableData: any[] = []; //table数据
  totalCount: number = 0; //分页总条数
  curPage: number = 1; //分页当前页
  pageSize: number = 10; //内置的分页每页条数
  searchKey: string = ""; //搜索keyword
  carList: any[] = [];
  companyId: string = "";
  companyList: any[] = [];
  deviceId: string = ""; //设备ID
  startTime: string = ""; //开始时间
  endTime: string = ""; //结束时间
  carNumber: string = ""; //车牌号码
  fileToUpload: File = null; //上传文件回调参数
  selectedCompanyId: string = "";
  selectedCompanyName: string = "";
  fileUp: string = "";

  selected: any[] = [];
  activeSelected: any[] = [];
  handleTitle = "添加";
  handleRow = {
    carNumber: "",
    deviceId: "",
    id: "",
    review: "",
    taskId: "",
    date: "",
    weight: "",
  }; //添加或者编辑的数据
  constructor(private jsonApiService: JsonApiService) {}

  ngOnInit() {
    this.initDate().then(() => this.load());
  }
  //公司选中回调
  companySelected(data) {
    this.selectedCompanyId = data.companyId;
    this.selectedCompanyName = data.companyName;
    this.deviceId = data.deviceId;
    this.carNumber = data.carNumber;
  }
  ngOnDestroy() {
    document.onclick = null;
  }
  //刷新
  refresh() {
    this.load();
  }
  //数据的导出
  export_totle() {
    this.startTime = $("#datetimepicker1").val();
    this.endTime = $("#datetimepicker2").val();
    if (this.startTime == "" || this.endTime == "") {
      this.jsonApiService.message("起始结束时间不能为空");
      return;
    }
    let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 0);
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message);
      return;
    }
    let reqdata =
      'param={"companyId":"' +
      this.selectedCompanyId +
      '","carNumber":"' +
      this.carNumber +
      '","startTime":"' +
      this.startTime +
      '","endTime":"' +
      this.endTime +
      '"}' +
      '&columns=[{"id":"carNumber","title":"车辆车牌号码"},{"id":"date","title":"过磅时间"},{"id":"weight","title":"载重量"}]';
    this.jsonApiService
      .http("weighbridge/allEmportFile.html", reqdata)
      .subscribe((data) => {
        var elemIF = document.createElement("iframe");
        elemIF.src = config.BaseURL + data.file;
        elemIF.style.display = "none";
        document.body.appendChild(elemIF);
        this.jsonApiService.message(data.message);
      });
  }
  add_data(val) {
    this.handleTitle = "添加";
    this.handleRow = {
      carNumber: "",
      deviceId: "",
      id: "",
      review: "",
      taskId: "",
      date: "",
      weight: "",
    };
    val.show();
    $('#uploadDate').val('');
  }
  editRow(row, val, _this) {
    this.handleTitle = "编辑";
    _this.stopPropagation();
    val.show();
    for (let item in this.handleRow) {
      this.handleRow[item] = row[item];
    }
    $("#rowDataForm").data("bootstrapValidator").resetForm();
  }
  cancelEdit(val) {
    val.hide();
    $("#rowDataForm").data("bootstrapValidator").resetForm();
  }
  editSubmit(val) {
    $("#rowDataForm").bootstrapValidator("validate");
    let isValid = $("#rowDataForm").data("bootstrapValidator").isValid();
    if (isValid) {
      let reqdata = "";
			this.handleRow.date = $('#uploadDate').val();
      for (let item in this.handleRow) {
        if (item == "carNumber") {
          reqdata += item + "=" + this.handleRow[item];
        } else {
          reqdata += "&" + item + "=" + this.handleRow[item];
        }
      }
      this.jsonApiService
        .http("weighbridge/updateWeighBridge.html", reqdata)
        .subscribe((result) => {
          this.jsonApiService.message(result.message);
          if (result.success) {
            this.load();
            this.cancelEdit(val);
          }
        });
    }
  }
  //数据提取
  get_data() {
    if (!this.carNumber) {
      this.jsonApiService.message("请选择车牌号码");
      return;
    }
    this.startTime = $("#datetimepicker1").val();
    this.endTime = $("#datetimepicker2").val();
    if (this.startTime == "" || this.endTime == "") {
      this.jsonApiService.message("起始结束时间不能为空");
      return;
    }
    let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 0);
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message);
      return;
    }
    let reqdata =
      'param={"carNumber":"' +
      this.carNumber +
      '","deviceId":"' +
      this.deviceId +
      '","startTime":"' +
      this.startTime +
      '","endTime":"' +
      this.endTime +
      '"}';
    this.jsonApiService
      .http("weighbridge/addDataFetch.html", reqdata)
      .subscribe((data) => {
        this.jsonApiService.message(data.message);
        if (data.success) {
          this.load();
        }
      });
  }
  //导入submit
  submitData(val) {
    let postParam = new FormData();
    postParam.append("file", this.fileToUpload);
    if (!this.fileToUpload) {
      this.jsonApiService.message("请上传文件");
      return false;
    }
    this.jsonApiService
      .form_http("weighbridge/upload.html", postParam)
      .subscribe((data) => {
        this.jsonApiService.message(data.message);
        if (data.success) {
          val.hide();
          this.fileToUpload = null;
          this.load();
        }
      });
  }
  //下载模板
  load_module() {
    var elemIF = document.createElement("iframe");
    elemIF.src =
      config.BaseURL + "resources/template/weighbridge-Template.xlsx";
    elemIF.style.display = "none";
    document.body.appendChild(elemIF);
  }
  clearFile() {
    this.fileUp = "";
  }
  //文件上传change回调
  fileChange(files: FileList) {
    this.fileToUpload = files.item(0);
    const isEXCEL =
      this.fileToUpload.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
      this.fileToUpload.type === "application/vnd.ms-excel";
    if (!isEXCEL) {
      this.jsonApiService.message("上传文件只能是 excel格式!");
      this.fileToUpload = null;
      return;
    }
  }
  cancelUp(val) {
    val.hide();
    this.fileToUpload = null;
  }
  getTime(date) {
    var year = date.getFullYear();
    var month =
      date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1;
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();

    return year + "-" + month + "-" + day;
  }
  initDate() {
    var that = this;
    return new Promise(function (resolve, reject) {
      System.import(
        "assets/js/datepicker/js/bootstrap-datetimepicker.min.js"
      ).then(() => {
        System.import(
          "assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js"
        ).then(() => {
          $("#datetimepicker1")
            .datetimepicker({
              //时间插件
              format: "yyyy-mm-dd",
              language: "zh-CN",
              autoclose: true,
              minView: 2,
            })
            .on("changeDate", function (e) {
              var date = e.date;
              var time = that.getTime(date);
              $("#datetimepicker2").datetimepicker("setStartDate", time);
            });
          $("#datetimepicker2")
            .datetimepicker({
              //时间插件
              format: "yyyy-mm-dd",
              language: "zh-CN",
              autoclose: true,
              minView: 2,
            })
            .on("changeDate", function (e) {
              var date = e.date;
              var time = that.getTime(date);
              $("#datetimepicker1").datetimepicker("setEndDate", time);
            });
          $("#uploadDate").on("changeDate", function(e){
						$("#rowDataForm").data("bootstrapValidator").resetForm();
					});
          common.initDatePicker('#uploadDate',0);
          var date = new Date();
          $("#datetimepicker2").val(that.getTime(date)); //当前时间
          date.setDate(date.getDate() - 7); //设置前一周
          $("#datetimepicker1").val(that.getTime(date));
          resolve();
        });
      });
    });
  }
  //查询
  search_data() {
    this.load();
  }
  //初始化加载list数据
  load() {
    this.selected = [];
    this.activeSelected = [];
    this.startTime = $("#datetimepicker1").val();
    this.endTime = $("#datetimepicker2").val();
    let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 0);
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message);
      return;
    }
    let reqdata: any = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        companyId: this.selectedCompanyId,
        carNumber: this.carNumber,
        startTime: this.startTime,
        endTime: this.endTime,
        deviceId: this.deviceId,
      },
    };
    reqdata = "gridPager=" + JSON.stringify(reqdata);
    this.jsonApiService
      .http("weighbridge/list.html", reqdata)
      .subscribe((data) => {
        this.tableData = data.exhibitDatas;
        this.totalCount = data.recordCount;
      });
  }
  //删除所选时间
  del_date() {
    this.startTime = "";
    this.endTime = "";
    $("#datetimepicker1").val("").change();
    $("#datetimepicker2").val("").change();
    $("#datetimepicker2").datetimepicker("setStartDate", null);
    $("#datetimepicker1").datetimepicker("setEndDate", null);
  }
  selectedRow(row, e, index) {
    if (this.activeSelected[index]) {
      this.activeSelected[index] = "";
    } else {
      this.activeSelected[index] = row.id;
    }
    var id = row.id;
    var index = $.inArray(id, this.selected);
    if (index === -1) {
      this.selected.push(id);
    } else {
      this.selected.splice(index, 1);
    }
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1;
    this.pageSize = e.rows;
    this.load();
  }
  //删除功能
  del_data() {
    var len = this.selected.length;
    if (len < 1) {
      this.jsonApiService.message("请选择需要删除的数据");
      return;
    }
    this.jsonApiService
      .confirm_message("此操作将永久删除数据,确认要删除?")
      .then(() => {
        var reqdata = "ids=" + this.selected.join(",");
        this.jsonApiService
          .http("weighbridge/deleteBatch.html", reqdata)
          .subscribe((result) => {
            this.jsonApiService.message(result.message);
            this.load();
          });
      });
  }
  /**
   * 提取西南水泥
   */
  get_XN_data() {
    this.startTime = $("#datetimepicker1").val();
    this.endTime = $("#datetimepicker2").val();
    this.jsonApiService.confirm_message("确定要提取西南水泥数据?").then(() => {
      let reqdata = {
        companyId: this.selectedCompanyId,
        deviceId: this.deviceId,
        startTime: this.startTime,
        endTime: this.endTime,
      };
      this.jsonApiService
        .http_obj("weighbridge/pickWeighBridgeByF.html", reqdata)
        .subscribe((result) => {
          this.jsonApiService.message(result.message);
        });
    });
  }
}
